﻿using AttributeDemo.CustomAttribute;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;

namespace AttributeDemo.UseAttribute
{
    public static class UseCustomAttribute
    {
        public static ValidateResult Validate<T>(this T t) where T : class
        {
            ValidateResult validateResult = new ValidateResult();
            bool isValid = true;
            List<string> errors = new List<string>();
            Type type = t.GetType();
            //属性
            foreach (var prop in type.GetProperties())
            {
                if (prop.IsDefined(typeof(AbstratValidateAttribute), true))
                {
                    var value = prop.GetValue(t);
                    foreach (AbstratValidateAttribute attribute in prop.GetCustomAttributes(typeof(AbstratValidateAttribute), true))
                    {
                        if (!attribute.Validate(value))
                        {
                            isValid = false;
                            errors.Add($"{prop.Name}校验失败");
                        }
                    }
                }
            }
            //方法
            foreach (var field in type.GetFields())
            {
                if (field.IsDefined(typeof(AbstratValidateAttribute), true))
                {
                    var value = field.GetValue(t);
                    foreach (AbstratValidateAttribute attribute in field.GetCustomAttributes(typeof(AbstratValidateAttribute), true))
                    {
                        if (!attribute.Validate(value))
                        {
                            isValid = false;
                            errors.Add($"{field.Name}校验失败");
                        }
                    }
                }
            }


            validateResult.IsValid = isValid;
            validateResult.Errors = errors;

            return validateResult;
        }
    }
}
